package com.yy.main.app.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yy.kit.collections.YYMapKits;
import com.yy.kit.string.YYStrKits;
import com.yy.main.app.mapper.TKeywordMapper;
import com.yy.main.app.mapper.TKeywordMessageMapper;
import com.yy.main.app.mapper.TMessageMapper;
import com.yy.main.app.service.IKeywordService;
import com.yy.pojo.base.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 关键字表，用户发送消息的时候，区分关键字做相应操作 服务实现类
 * </p>
 *
 * @author 杨阳
 * @since 2017-09-20
 */
@Service("iKeywordService")
public class KeywordServiceImpl implements IKeywordService {

    @Autowired
    private TKeywordMapper tKeywordMapper;
    @Autowired
    private TKeywordMessageMapper tKeywordMessageMapper;
    @Autowired
    private TMessageMapper tMessageMapper;

    @Override
    @Transactional
    public Map<String, Object> savekeyword(TKeyword key, String msgid) {
        Map<String, Object> result = YYMapKits.createHashMap();
        if (1 == key.getOperation()) {// 调用服务，那么将消息类型设置为空串
            key.setType(0);
        }
        if (YYStrKits.isBlank(key.getId()) || "-1".equals(key.getId())) {// 增加
            result = add(key);
            String id = (String) result.get("id");
            keywordsAndMessages(id, msgid);
        } else {// 修改
            result = update(key);
            keywordsAndMessages(key.getId(), msgid);
        }
        return result;
    }

    /**
     * <p>
     * 关联关键字与消息
     * </p>
     *
     * @param keywordid 关键字id
     * @param msgid     消息id串，以逗号分隔1,2,3
     */
    private void keywordsAndMessages(String keywordid, String msgid) {
        // 增加或修改完关键字以后，关联关键字与消息
        if (YYStrKits.isNotBlank(msgid)) {
            // 先将原来的关联删除掉
            TKeywordMessageExample example = new TKeywordMessageExample();
            example.createCriteria().andKeyword_idEqualTo(keywordid);
            tKeywordMessageMapper.deleteByExample(example);

            String[] msgids = msgid.split(",");
            for (int i = 0, length = msgids.length; i < length; i++) {
                String mid = msgids[i];
                TKeywordMessage km = new TKeywordMessage();
                km.setId(YYStrKits.getTableId());
                km.setMessage_id(mid);
                km.setKeyword_id(keywordid);
                km.setSeq(i + 1);
                tKeywordMessageMapper.insert(km);
            }
        }
    }

    /**
     * <p>
     * 修改关键字
     * </p>
     *
     * @param key 关键字实体
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月22日
     */
    private Map<String, Object> update(TKeyword key) {
        Map<String, Object> result = YYMapKits.createHashMap();

        // 判断帐号是否重复
        TKeywordExample example = new TKeywordExample();
        example.createCriteria()
                .andKeycodeEqualTo(key.getKeycode())
                .andIdNotEqualTo(key.getId());

        long accountCount = tKeywordMapper.countByExample(example);
        if (accountCount > 0) {
            result.put("success", Boolean.FALSE);
            result.put("msg", "关键字KEYCODE重复，请重试!!");
            return result;
        }

        key.setUpdate_date(new Date());
        Integer b = tKeywordMapper.updateByPrimaryKey(key);
        if (b > 0) {
            result.put("success", Boolean.TRUE);
            result.put("msg", "修改关键字成功!!");
            result.put("id", key.getId());
        } else {
            result.put("success", Boolean.FALSE);
            result.put("msg", "修改关键字失败，请重试!!");
        }
        return result;
    }

    /**
     * <p>
     * 增加关键字
     * </p>
     *
     * @param key 关键字实体
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月22日
     */
    private Map<String, Object> add(TKeyword key) {
        Map<String, Object> result = YYMapKits.createHashMap();

        String id = YYStrKits.getTableId();
        key.setId(id);
        // 判断关键表中的key是否重复
        TKeywordExample example = new TKeywordExample();
        example.createCriteria().andKeycodeEqualTo(key.getKeycode());
        long accountCount = tKeywordMapper.countByExample(example);
        if (accountCount > 0) {
            result.put("success", Boolean.FALSE);
            result.put("msg", "关键字KEY重复，请重试!!");
            return result;
        }
        key.setCreate_date(new Date());
        Integer b = tKeywordMapper.insert(key);
        if (b > 0) {
            result.put("success", Boolean.TRUE);
            result.put("msg", "增加关键字成功!!");
            result.put("id", id);
        } else {
            result.put("success", Boolean.FALSE);
            result.put("msg", "增加关键字失败，请重试!!");
        }
        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> delkeyword(String id) {
        Map<String, Object> map = YYMapKits.createHashMap();
        Integer b = tKeywordMapper.deleteByPrimaryKey(id);
        if (b > 0) {
            // 删除关键字后，再删除与消息关联表中的数据
            TKeywordMessageExample example = new TKeywordMessageExample();
            example.createCriteria().andKeyword_idEqualTo(id);
            tKeywordMessageMapper.deleteByExample(example);

            map.put("success", Boolean.TRUE);
            map.put("msg", "删除成功!");
            return map;
        } else {
            map.put("success", Boolean.FALSE);
            map.put("msg", "删除失败，请重试!");
            return map;
        }
    }

    @Override
    public TKeyword selectById(String id) {
        return tKeywordMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo selectMessageByKeywordId(Integer page, Integer limit, String keywordid) {
        PageHelper.startPage(page, limit);
        List<TMessage> list = tMessageMapper.selectMessageByKeywordId(keywordid);
        return new PageInfo(list);
    }

    @Override
    public List<TMessage> selectMessageByKeywordId(String keywordid) {
        return tMessageMapper.selectMessageByKeywordId(keywordid);
    }

}
